package com.tg.base.concurrent.lock.reentrantLock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock的Condition测试
 * Created by MagicBook on 2019/12/25.
 */
public class ReentrantLockConditionTest {
    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {

        lock.lock();
        new Thread(new SignalThread(lock, condition)).start();
        System.out.println("主线程等待通知");
        try {
            condition.await();
        } finally {
            lock.unlock();
        }
        System.out.println("主线程恢复运行");
    }

    static class SignalThread implements Runnable {

        private Lock mylock;

        private Condition myCondition;

        public SignalThread(Lock mylock, Condition myCondition) {
            this.mylock = mylock;
            this.myCondition = myCondition;
        }

        @Override
        public void run() {
            mylock.lock();
            try {
                myCondition.signal();
                System.out.println("子线程通知");
            } finally {
                mylock.unlock();
            }
        }
    }
}
